<script>
    import { onDestroy, tick } from "svelte";
    import { ImageOperation } from "../utils/imageOperation";

    import ImagePicker from "./components/ImagePicker.svelte";

    let canvas;
    let canvasWidth = 0;
    let canvasHeight = 0;
    let resultImageArea;

    const pickedHandler = async ({ detail }) => {
        const { img: image } = detail;
        canvasWidth = image.width;
        canvasHeight = image.height;
        await tick();

        const ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        const imageData = ctx.getImageData(0, 0, image.width, image.height);

        const resultCtx = resultImageArea.getContext("2d");
        // picture(imageData, resultCtx);
        animation(imageData, resultCtx);
    };

    // 静态图片
    function picture(imageData, resultCtx) {
        const nimgData =
            // .invert()
            // .compress(4, 4)
            // .expand(8, 8)
            new ImageOperation(imageData).grayscale().imageData;
        resultCtx.putImageData(nimgData, 0, 0);
    }

    // 动画
    let frame;
    function animation(imageData, resultCtx) {
        frame = requestAnimationFrame(loop);

        function loop(t) {
            frame = requestAnimationFrame(loop);

            const nimgData = new ImageOperation(imageData).colorful(
                t
            ).imageData;

            resultCtx.putImageData(nimgData, 0, 0);
        }
    }
    onDestroy(() => cancelAnimationFrame(frame));
</script>

<canvas
    bind:this={canvas}
    width={canvasWidth}
    height={canvasHeight}
    class="image-data-canvas-hidden"
/>
<ImagePicker on:picked={pickedHandler} />
<hr />
<canvas
    bind:this={resultImageArea}
    width={canvasWidth}
    height={canvasHeight}
    class="result-image-canvas-area"
/>

<style>
    .image-data-canvas-hidden {
        display: none;
    }
    .result-image-canvas-area {
        border: 1px dashed;
        padding: 5px;
    }
</style>
